package com.example.controller;

import com.example.entity.Goods;
import com.example.service.GoodsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsHandler {

    @Autowired
    private GoodsService goodsService;

    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("goods");
        modelAndView.addObject("list",goodsService.findAll());
        return modelAndView;
    }

    @GetMapping(value="/get",produces ="application/json;charset=utf-8")
    @ResponseBody
    @CrossOrigin
    public String getGoods() throws JsonProcessingException {

        // 创建一个Jackson的对象映射器,用来解数据
        ObjectMapper objectMapper = new ObjectMapper();
        //创建实体对象
        List<Goods> books = goodsService.findAll();
        //将对象解析成为json格式
        String jsonStr = objectMapper.writeValueAsString(books);
        return jsonStr;
    }
}
